import pygame
import sys
import random
import copy

colors = [(136,84,243),
		(255,121,174),
		(99,255,186),
		(255,249,130),
		(99,155,255)
		]

pygame.init()

class Apple():
	def __init__(self):
		self.seed = [random.randint(0,19), random.randint(0, 19)]
		self.color = colors[1]
	def regenerate(self):
		self.seed = [random.randint(0,19), random.randint(0, 19)]
	def geteaten(self):
		self.seed = []

class Snake():
	def __init__(self):
		self.size = [[10, 10]]
		self.wheremove = "right"
	def grow(self):
		if len(self.size) > 1:
			if self.size[-1][0] > self.size[-2][0]:
				self.size.append([self.size[-1][0]+1,self.size[-1][1]])
			elif self.size[-1][0] < self.size[-2][0]:
				self.size.append([self.size[-1][0]-1,self.size[-1][1]])
			elif self.size[-1][0] > self.size[-2][0]:
				self.size.append([self.size[-1][0]-1,self.size[-1][1]])
			elif self.size[-1][0] < self.size[-2][0]:
				self.size.append([self.size[-1][0]+1,self.size[-1][1]])
			elif self.size[-1][1] > self.size[-2][1]:
				self.size.append([self.size[-1][0],self.size[-1][1]+1])
			elif self.size[-1][1] < self.size[-2][1]:
				self.size.append([self.size[-1][0],self.size[-1][1]-1])
			elif self.size[-1][0] > self.size[-2][0]:
				self.size.append([self.size[-1][0],self.size[-1][1]-1])
			else:
				self.size.append([self.size[-1][0],self.size[-1][1]+1])
		else:
			match self.wheremove:
				case 'right':
					self.size.append([self.size[0][0]-1, self.size[0][1]])
				case 'left':
					self.size.append([self.size[0][0]+1, self.size[0][1]])
				case 'up':
					self.size.append([self.size[0][0], self.size[0][1]+1])
				case 'down':
					self.size.append([self.size[0][0], self.size[0][1]-1])
	def move(self):
		match self.wheremove:
			case "right":
				self.size[0][0]+=1
			case "left":
				self.size[0][0]-=1
			case "up":
				self.size[0][1]-=1
			case "down":
				self.size[0][1]+=1
	def intersection(self):
		inter = set({})
		for i in self.size:
			inter.add(tuple(i))
		if len(inter) < len(self.size):
			self.size = []
		inter = set({})
		for i in self.size:
			if i[0]<0 or i[0]>19 or i[1]<0 or i[1]>19:
				self.size = []

fontik = pygame.font.Font(None, 30)
screen = pygame.display.set_mode((400, 500), pygame.SCALED)
gamesurf = pygame.Surface((400,400))
FPS = 60
clock = pygame.time.Clock()
tile = 20
snake = Snake()
apple = Apple()
timer = 0
canMove = True
needTogrow = False
isGameover = False

while True:
	timer +=1
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			sys.exit()
		if event.type == pygame.KEYDOWN:
			if canMove:
				if event.key == pygame.K_LEFT and snake.wheremove != "right":
					snake.wheremove = "left"
					canMove = False
				if event.key == pygame.K_RIGHT and snake.wheremove != "left":
					snake.wheremove = "right"
					canMove = False
				if event.key == pygame.K_UP and snake.wheremove != "down":
					snake.wheremove = "up"
					canMove = False
				if event.key == pygame.K_DOWN and snake.wheremove != "up":
					snake.wheremove = "down"
					canMove = False
			if event.key == pygame.K_SPACE and isGameover:
				snake = Snake()
				apple.regenerate()
				isGameover = False
	screen.fill(pygame.Color('black'))
	gamesurf.fill(pygame.Color('black'))
	if not isGameover:
		scoretext = fontik.render(f'Ваш счет: {len(snake.size)}', True, colors[0])
		screen.blit(scoretext, (0, 20))
	else:
		gameovertext = 'Игра окончена!\nНажмите SPACEBAR, чтобы\nначать заново'
		lines = gameovertext.splitlines()
		for i, l in enumerate(lines):
			screen.blit(fontik.render(l, True, colors[0]), (0, 20 + tile*i))
	if apple.seed != []:
		pygame.draw.rect(gamesurf, apple.color, (apple.seed[0]*tile, apple.seed[1]*tile, tile, tile))
	for i in snake.size:
		pygame.draw.rect(gamesurf, colors[2], (i[0]*tile, i[1]*tile, tile, tile))
		if i == apple.seed:
			apple.geteaten()
			apple.regenerate()
			snakesizecopy = copy.deepcopy(snake.size)
			snake.grow()
			if snake.size == []:
				snake.size = snakesizecopy
				needTogrow = True

	if timer >=15 and snake.size != []:
		saved = []
		for i in range(len(snake.size)):
			if i != 0:
				if i == 1:
					saved.append(copy.deepcopy(snake.size[i]))
					snake.size[i] = copy.deepcopy(snake.size[i-1])
				else:
					saved.append(copy.deepcopy(snake.size[i]))
					snake.size[i] = saved[i-2]
		saved = []
		snake.move()
		if needTogrow:
			snake.grow()
			needTogrow = False
		canMove = True
		timer = 0
	if snake.size == []:
		isGameover = True
	for i in range(20):
		for j in range(20):
			pygame.draw.rect(gamesurf, colors[0], (i*tile, j*tile,
			tile, tile), 1)
	snake.intersection()
	screen.blit(gamesurf, (0,100))
	pygame.display.update()
	clock.tick(FPS)